package cn.growthgate.fgo.util;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpStatus;

import com.alibaba.fastjson.JSON;

public class HttpUtils {

	public static String get(String url) throws Exception {
		return get(url, null);
	}

	public static String get(String url, Map<String, Object> params) throws Exception {
		try (CloseableHttpClient client = HttpClients.createDefault()) {
			if (MapUtils.isNotEmpty(params)) {
				Map<String, String[]> map = new HashMap<>();
				params.forEach((k, v) -> {
					Object[] array = ArrayUtils.toObject(v);
					map.put(k, ArrayUtils.toStringArray(array));
				});
				url = UrlUtils.addParams(url, map);
			}
			HttpGet request = new HttpGet(new URI(url));
			try (CloseableHttpResponse response = client.execute(request)) {
				if (HttpStatus.OK.value() == response.getStatusLine().getStatusCode()) {
					return EntityUtils.toString(response.getEntity());
				} else {
					throw new RuntimeException("请求失败：" + url);
				}
			}
		}
	}

	public static String post(String url) throws Exception {
		return post(url, null);
	}

	public static String post(String url, Map<String, Object> params) throws Exception {
		try (CloseableHttpClient client = HttpClients.createDefault()) {
			HttpPost request = new HttpPost(new URI(url));
			if (MapUtils.isNotEmpty(params)) {
				request.setEntity(new StringEntity(JSON.toJSONString(params), StandardCharsets.UTF_8));
			}
			try (CloseableHttpResponse response = client.execute(request)) {
				if (HttpStatus.OK.value() == response.getStatusLine().getStatusCode()) {
					return EntityUtils.toString(response.getEntity());
				} else {
					throw new RuntimeException("请求失败：" + url);
				}
			}
		}
	}

}
